//
//  HMMainTabBar.swift
//  iOSWeibo12
//
//  Created by Admin on 16/9/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class HMMainTabBar: UITabBar {

    // 属性
    /// 按钮点击的闭包 (() -> ())? 是一个可选
    var composeClosure: (() -> ())?
    
    //: 懒加载撰写按钮
    lazy var composeButton: UIButton = {
        let button = UIButton()
        
        // 添加背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: UIControlState.normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        
        self.addSubview(button)
        
        // 撰写按钮添加点击事件
        button.addTarget(self, action: #selector(composeClick), for: UIControlEvents.touchUpInside)
        
        return button
    }()
    
    /// 撰写微博按钮被点击
    func composeClick() {
        // UIView是不能直接弹出控制器的
        // 调用闭包, ? 如果闭包没有值,就不执行
        composeClosure?()
    }
    
    // 定义tabBar按钮总数 = 5
    private let buttonCount = 5
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 计算每个tabBarItem的宽度
        let width = bounds.width / CGFloat(buttonCount)
        
        // 创建每个tabBarItem的frame
        let frame = CGRect(x: 0, y: 0, width: width, height: bounds.height)
        
        var index = 0
        for view in subviews {
            // 判断是否是 UITabBarButton
            let cls = NSClassFromString("UITabBarButton")
            
            if view.isKind(of: cls!) {
                view.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: frame.height)
                
                //: 留出第2个位置给撰写按钮
                index += 1
                if index == 2 {
                    index += 1
                }
            }
        }
        
        // 设置撰写按钮到中间位置
        composeButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: frame.height)
    }
}
